<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Province;
use App\Models\City;
use App\Models\District;
use Illuminate\Http\Request;

class AddressController extends Controller
{
    /**
     * 获取所有省份
     */
    public function provinces()
    {
        $provinces = Province::active()
            ->ordered()
            ->select(['id', 'name', 'code'])
            ->get();

        return response()->json([
            'success' => true,
            'data' => $provinces
        ]);
    }

    /**
     * 根据省份获取城市
     */
    public function cities(Request $request)
    {
        $request->validate([
            'province_id' => 'required|integer|exists:provinces,id'
        ]);

        $cities = City::active()
            ->byProvince($request->province_id)
            ->ordered()
            ->select(['id', 'name', 'code'])
            ->get();

        return response()->json([
            'success' => true,
            'data' => $cities
        ]);
    }

    /**
     * 根据城市获取区县
     */
    public function districts(Request $request)
    {
        $request->validate([
            'city_id' => 'required|integer|exists:cities,id'
        ]);

        $districts = District::active()
            ->byCity($request->city_id)
            ->ordered()
            ->select(['id', 'name', 'code'])
            ->get();

        return response()->json([
            'success' => true,
            'data' => $districts
        ]);
    }
}